import hashlib
import os
import requests
from http import HTTPStatus

'''
API名称：文档上传
API路径：https://dashscope.aliyuncs.com/api/v2/apps/zhiwen-file/apply_upload_lease
        https://dashscope.aliyuncs.com/api/v2/apps/zhiwen-file/submit_parse_file
环境要求：Python >= 3.7
'''


def get_filename_with_split(url):
    """
    使用字符串的 split 方法提取文件名
    """
    # 1. 用 '?' 分割，取第一部分
    path_part = url.split('?')[0]
    # 2. 用 '/' 分割，取最后一部分
    filename = path_part.split('/')[-1]
    return filename


publicfilename=""
def uploadfile(filename):
    publicfilename=filename
    apply_lease_url = "https://dashscope.aliyuncs.com/api/v2/apps/zhiwen-file/apply_upload_lease"
    submit_file_url = "https://dashscope.aliyuncs.com/api/v2/apps/zhiwen-file/submit_parse_file"
    request_headers = {
        "Authorization": "sk-127dd2cb8e454d16b58f376d820eec63",
        "Content-Type": "application/json"
    }
    file_path = "./"+filename
    file_name = os.path.basename(file_path)
    file_size = os.path.getsize(file_path)
    if file_size>537910512:
        import splitn
        n = file_size//537910512 + 2
        splitn.split_video(filename,n)
        exit()
    with open(file_path, 'rb') as f:
        md5 = hashlib.md5()
        while True:
            data = f.read(4096)  # 每次读取4KB数据
            if not data:
                break
            md5.update(data)
    file_md5 = md5.hexdigest()

    # 1. 申请租约
    response = requests.post(apply_lease_url,
                             json={
                                 "fileName": file_name,
                                 "sizeBytes": file_size,
                                 "md5": file_md5
                             },
                             headers=request_headers)
    lease_data = {}
    if response.status_code == HTTPStatus.OK:
        print("1. Lease applied successfully.")
        print("正在上传，别着急")
        lease_data = response.json()['data']
    else:
        print(f'response={response.json()}')
        print(f'code={response.status_code}')

    # 2. 上传文档
    upload_headers = {
        "X-bailian-extra": lease_data['param']['headers']['x-bailian-extra'],
        "Content-Type": lease_data['param']['headers']['Content-Type']
    }
    with open(file_path, 'rb') as file:
        # 下方设置请求方法用于文档上传，需与您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param中Method字段的值一致
        response = requests.put(lease_data['param']['url'], data=file, headers=upload_headers)
    if response.status_code == HTTPStatus.OK:
        print("2. File uploaded successfully.")
    else:
        print(f"Failed to upload the file. ResponseCode: {response.status_code}")

    # 3.提交解析
    response = requests.post(submit_file_url,
                             json={
                                 'leaseId': lease_data['lease_id']
                             },

                             headers=request_headers)
    if response.status_code == HTTPStatus.OK:
        print("3. File submit parse successfully.")
        link = response.json()['data']['url']
        link = link.removeprefix("https://")
        print(link)
        print("上述为下载链接，注意不要直接点击，而是双击链接，再长按复制到浏览器")
        print("file:///sdcard/Download/"+get_filename_with_split(link))
        print("上述为本地文件名，用于下载后打开")
    else:
        print(f'response={response.json()}')
        print(f'code={response.status_code}')
if __name__ == "__main__":
    uploadfile(input("文件名"))
